package com.blog.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.common.domain.dto.CommentDto;
import com.blog.common.domain.entity.UserInfo;
import com.blog.common.mapper.dao.UserInfoMapper;
import com.blog.web.service.UserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author Valerie
 * @since 2023-02-18
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public void insertUserByComment(CommentDto commentDto) {
        UserInfo userInfo = new LambdaQueryChainWrapper<>(userInfoMapper)
                .eq(UserInfo::getEmail, commentDto.getEmail())
                .last("limit 1")
                .one();
        if (Objects.nonNull(userInfo)){
            // 修改
            userInfo.setNickname(commentDto.getNickname());
            userInfo.setWebSite(commentDto.getWebsite());
            UserInfoServiceImpl userInfoService = SpringUtil.getBean(this.getClass());
            userInfoService.saveOrUpdate(userInfo);
            commentDto.setUserId(userInfo.getId());
        }else {
            long id = IdUtil.getSnowflakeNextId();
            // 新增
            userInfo = UserInfo.builder()
                    .id(id)
                    .email(commentDto.getEmail())
                    .nickname(commentDto.getNickname())
                    .webSite(commentDto.getWebsite())
                    .build();
            boolean save = this.save(userInfo);
            if (save){
                commentDto.setUserId(userInfo.getId());
            }
        }
    }
}
